from Products.KnowledgeEngine.KERL.Tokens.Token import Token
from Products.KnowledgeEngine.KERL.Operators import Operator, SimpleOperator
from DateTime import DateTime
from Products.KnowledgeEngine.Services.MySQLFiveAssessmentStorageService.MySQLFiveAssessmentStorageService import qstr, qlist

class Responsible(SimpleOperator):
    
    _opname = "responsible"
    
    def toEnglish( self ):
        return "%s is reponsible" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                                            
        return  assessment.getResponsible() == str(self.b)
   
    def toSQL( self ): 
        
        compare = self.b.getObject()
        
        return "responsible = %s" % qstr( compare )

class CreatedBy(SimpleOperator):
    
    _opname = "createdby"
    
    def toEnglish( self ):
        return "Assessment was created by %s" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                                            
        return  assessment.getCreatedBy() == str(self.b)
   
    def toSQL( self ): 
        
        compare = self.b.getObject()
        
        return "createdBy = %s" % qstr( compare )
    
class CreatedByGroup(SimpleOperator):
    
    _opname = "createdbygroup"
    
    def toEnglish( self ):
        return "Assessment was created by group %s" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                                             
        checkGroup = self.b.getObject()
        
        context = assessment.getModel()
        
        user_id = assessment.getCreatedBy()    
                   
        user    = context.portal_membership.getMemberById( user_id )        
        
        if not user:
            return False
        
        groups  = user.getGroups()
        
        return (checkGroup in groups)
            
    def toSQL( self ): 
        
        assessment = self.a.getObject()
        context    = assessment.getModel()
        
        group_id = self.b.getObject()
        group = context.portal_groups.getGroupById( group_id )
        
        members = group.getMembers()
        
        return "createdBy IN (%s)" % qlist( members )     

class CheckedOutBy(SimpleOperator):
    
    _opname = "checkedoutby"
    
    def toEnglish( self ):
        return "Assessment was checked out by %s" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                                            
        return  assessment.getCheckedOutBy() == str(self.b)
   
    def toSQL( self ): 
        
        compare = self.b.getObject()
        
        return "checkedOutBy = %s" % qstr( compare )


class IsCheckedOut(SimpleOperator):
    
    _opname = "ischeckedout"
    
    def toEnglish( self ):
        return "Assessment is checked out"
    
    def execute( self, assessment ):
                                            
        return  assessment.getCheckedOutBy() and True or False
   
    def toSQL( self ): 
        
        compare = self.b.getObject()
        
        return "( checkedOutBy is not null and checkedOutBy != '' )" % qstr( compare )


class CreatedBefore(SimpleOperator):
    
    _opname = "createdbefore"
    
    def toEnglish( self ):
        return "Assessment was created before %s" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                                    
        compare = DateTime( self.b.getObject() )        
        return  assessment.getInstantCreated() < compare
   
    def toSQL( self ):
        
        compare = DateTime( self.b.getObject() )        
        
        return "instantCreated < '%s'" % compare.strftime("%Y-%m-%d %H:%M:%S")  

    
class CreatedAfter(SimpleOperator):
    
    _opname = "createdafter"
    
    def toEnglish( self ):
        return "Assessment was created after %s" % (self.b.toEnglish())    
    
    def execute( self, assessment ):
                            
        compare = DateTime( self.b.getObject() )        
        return  assessment.getInstantCreated() > compare
        
    def toSQL( self ):
        
        compare = DateTime( self.b.getObject() )        
        
        return "instantCreated > '%s'" % compare.strftime("%Y-%m-%d %H:%M:%S")  

class ModifiedBefore(SimpleOperator):
    
    _opname = "modifiedbefore"
    
    def toEnglish( self ):
        return "Assessment was modified before %s" % (self.b.toEnglish())
    
    def execute( self, assessment ):
                        
        compare = DateTime( self.b.getObject() )        
        return  assessment.getInstantModified() < compare    
    
class ModifiedAfter(SimpleOperator):
    
    _opname = "modifiedafter"
    
    def toEnglish( self ):
        return "Assessment was modified after %s" % (self.b.toEnglish())    

    def execute( self, assessment ):
                        
        compare = DateTime( self.b.getObject() )        
        return  assessment.getInstantModified() > compare
    
class InRepository(SimpleOperator):
    
    _opname = "inrepository"
    
    def toEnglish( self  ):
        return "Assessment is in repository " + self.b.toEnglish()
    
    def execute( self, assessment ):
        
        return str(self.b) in assessment.getRepositoryIdentities()
    
    def toSQL( self ):
        
        return """
assessmentIdentity IN (
    SELECT assessmentIdentity 
    FROM repositories
    WHERE repositoryIdentity = %s   
)""" % qstr( self.b )


class NotInRepository(InRepository):
    
    _opname = "notinrepository"
    
    def toEnglish( self  ):
        return "Assessment is not in repository " + self.b.toEnglish()
    
    def execute( self, assessment ):
        
        return not InRepository.execute( self, assessment )
    
    def toSQL( self ):
        
        return "NOT (" + InRepository.toSQL( self ) + ")"


class AssessmentToken(Token):
    
    operators = dict(Token.operators)
    operators.update({
        'createdbefore'  : CreatedBefore,
        'createdafter'   : CreatedAfter,
        'modifiedbefore' : ModifiedBefore,
        'modifiedafter'  : ModifiedAfter,     
        'inrepository'   : InRepository, 
        'notinrepository': NotInRepository,
        'createdby'      : CreatedBy,
        'checkedoutby'   : CheckedOutBy,
        'createdbygroup' : CreatedByGroup,
        'responsible'    : Responsible,
        
        'ischeckedout'   : IsCheckedOut,
        
        
    })
    
    def __init__(self, namespace):
        
        self.namespace = namespace
    
    def toEnglish(self):
        """ Compiles this token into english """
        
        return "Assessment"
        
    def toKERL(self):
        return "'assessment'"
        